<script setup lang="ts">
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
import { RegistrationOrderApi } from '@/api/registration-order';
import AuthBar from '@/components/authBar/index.vue';
import { PAY_TYPE } from '@/enums/pay.enums';
import { useUserStore } from '@/store/userStore';
import { buildAssetSource } from '@/utils';
import { isUndefined } from '@/utils/is.utils';
import { currRoute, withQueryString } from '@/utils/router.utils';
import Steps from './components/steps.vue';
import { useDoctorInfo } from './hooks/useDoctorInfo';
import { useRegistrationProjectFee } from './hooks/useRegistrationProjectFee';

const { query } = currRoute();

const { doctor } = useDoctorInfo();

const { totalAmount, feeList } = useRegistrationProjectFee(doctor);

const selectPayType = ref();

// 定义支付方式数组
const payMethods = [
  {
    type: PAY_TYPE.BANK_CARD,
    title: '银联支付',
    image: 'bank-card.png',
    imageClass: 'h-129 w-129',
    tags: ['云闪付', '银行卡', 'NFC闪付']
  },
  {
    type: PAY_TYPE.ALIPAY,
    title: '支付宝支付',
    image: 'alipay.png',
    imageClass: 'h-118 w-118',
    tags: ['扫码支付', '人脸支付', '亲情码']
  },
  {
    type: PAY_TYPE.WECHAT,
    title: '微信支付',
    image: 'wechat.png',
    imageClass: 'h-106 w-106',
    tags: ['扫码支付', '人脸支付', '亲情码']
  },
  {
    type: PAY_TYPE.MEDICAL_INSURANCE,
    title: '医保支付',
    image: 'yibao-pay.png',
    imageClass: 'h-120 w-120',
    tags: ['医保码', '人脸支付', '医保卡']
  }
];

function onSelectPayType(type: PAY_TYPE) {
  selectPayType.value = type;
}

const { userInfo } = storeToRefs(useUserStore());

// 创建订单
function createOrder() {
  uni.showLoading({
    title: '创建订单中',
    mask: true
  });

  const { patientId, patientName } = userInfo.value;
  const { appointmentDateTime, timePeriod, appointmentTimeId } = query;
  const { clinicRoomId, sectionId, sectionName, doctorId, doctorName } = doctor.value;

  return RegistrationOrderApi.create({
    patientId,
    patientName,
    appointmentDate: dayjs(Number(appointmentDateTime)).format('YYYY-MM-DD'),
    clinicRoomId,
    departmentId: sectionId,
    departmentName: sectionName,
    doctorId,
    doctorName,
    timePeriod,
    appointmentTimeId: Number(appointmentTimeId),
    paymentType: PAY_TYPE.ALIPAY,
    registrationFeeId: feeList.value.id
  }).finally(() => {
    uni.hideLoading();
  });
}

const confirmLoading = ref(false);
function handleConfirm() {
  if (isUndefined(selectPayType.value)) {
    uni.showToast({
      title: '请选择支付方式',
      icon: 'none'
    });
    return;
  }
  confirmLoading.value = true;
  // TODO 判断选择的支付方式
  createOrder().then(res => {
    uni.navigateTo({
      url: withQueryString('/pages/pay/alipayCode', {
        orderNo: res.orderNo,
        payOrderId: res.payOrderId,
        totalAmount: totalAmount.value,
        redirectUrl: '/pages/appointmentRegistration/registrationSuccess'
      })
    });
  }).finally(() => {
    confirmLoading.value = false;
  });
}
</script>

<template>
  <view class="registration-payment flex-col">
    <Steps :current="5" />
    <AuthBar />
    <view class="flex-1 overflow-auto px-48 pt-30">
      <view class="registration-payment__info">
        <view class="registration-payment__cell flex justify-between">
          <view class="registration-payment__title">
            挂号费用
          </view>
          <view class="registration-payment__cost">
            ¥{{ totalAmount }}
          </view>
        </view>
        <view class="mt-30 text-24 text-[var(--secondary-text-color)]">
          <view>费用包含：挂号费、治疗费及其他费用</view>
          <view class="mt-20">
            医保患者请先插入医保卡，可享受医保报销
          </view>
        </view>
      </view>

      <view class="pay-list">
        <view
          v-for="method in payMethods"
          :key="method.type"
          class="pay-item"
          :class="{ 'pay-item--active': selectPayType === method.type }"
          @click="onSelectPayType(method.type)"
        >
          <view class="pay-item__cover">
            <image :src="buildAssetSource(method.image)" :class="method.imageClass" />
          </view>
          <view class="pay-item__content">
            <view class="pay-item__title">
              {{ method.title }}
            </view>
            <view class="pay-item__tags">
              <view v-for="(tag, index) in method.tags" :key="index" class="pay-item__tag">
                {{ tag }}
              </view>
            </view>
          </view>
        </view>
      </view>

      <view class="mb-50 flex-center">
        <view class="confirm-btn">
          <wd-button block :loading="confirmLoading" @click="handleConfirm">
            确认支付 ¥{{ totalAmount }}
          </wd-button>
        </view>
      </view>
    </view>
  </view>
</template>

<route type="page" lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '预约挂号',
    navigationStyle: 'custom'
  }
}
</route>

<style lang="scss" scoped>
.registration-payment {
  background-color: var(--bg-color);
  height: 100%;

  .registration-payment__info {
    background-color: #fff;
    border-radius: 20px;
    padding: 50px 42px 50px 32px;

    .registration-payment__cell {
      font-size: 46px;
      font-weight: bold;

      color: var(--text-color);
      border-bottom: 1px solid #c6dafa;
      padding-bottom: 20px;
    }
  }

  .pay-list {
    margin-top: 38px;

    .pay-item {
      @apply flex items-center;
      background: rgba(247, 250, 254, 0.5);
      border-radius: 20px;
      margin-bottom: 20px;
      padding: 30px 35px;

      .pay-item__cover {
        @apply flex-center;
        width: 129px;
        height: 129px;
      }

      .pay-item__content {
        flex: 1;
        margin-left: 26px;

        .pay-item__title {
          font-size: 36px;
          font-weight: bold;

          color: var(--text-color);
        }

        .pay-item__tags {
          @apply flex items-center;
          margin-top: 20px;
          .pay-item__tag {
            background: rgba(247, 250, 254, 0.5);
            border: 2px solid rgba(255, 255, 255, 0.5);
            border-radius: 100px;
            padding: 4px 20px;
            margin-right: 10px;
            font-size: 26px;
            color: var(--secondary-text-color);
          }
        }
      }

      &.pay-item--active {
        background: #fff;

        .pay-item__tags {
          .pay-item__tag {
            background: rgba(209, 229, 255, 0.5);
          }
        }
      }
    }
  }

  .confirm-btn {
    width: 708px;
    --wot-button-medium-height: 124px;
    --wot-button-medium-fs: 42px;
    --wot-button-medium-loading: 36px;
    margin-top: 59px;

    :deep(.wd-button) {
      font-weight: bold;
    }
  }
}
</style>
